package model;

import util.IDGenerator;
import Repository.MarketingRepository;
import Repository.Repository;
import Repository.RepositoryFactory;
import constants.SMSConstants;
import controller.AccountController;
import factory.SMSObjectFactory;


public class Raw implements SMSObjectState {

	private final String NAME = "Raw";
	RuleSelector ruleSelector;
	NextStateCalculator stateCalculator;
	Repository repository;

	
	@Override
	public void execute(SMSObject smsObj) {
		if(smsObj instanceof Lead){
			//System.out.println("Executing Raw State...");
		    ruleSelector =  new ImportRuleSelector(smsObj);
			stateCalculator = new NextStateCalculator();
			SMSObjectState newState = stateCalculator.getNextState(smsObj,ruleSelector);
			//System.out.println("New state..." + newState.getStateName());
			
			if(newState.getStateName().equals(NAME)){
				System.out.println("****Lead cannot be imported as the object doesnot pass the rules****");
				return;
			}
			smsObj.setCurrentState(newState);
			
			//System.out.println("Creating new lead object..." );
			SMSObjectFactory factory = new SMSObjectFactory();
			
			
			Lead lead = (Lead)factory.createSMSObject(SMSConstants.LEAD);
			Lead l = (Lead)smsObj;
			
			AccountController accCon = new AccountController("insert");
			Account account = (Account) accCon.createAccount();
			
			lead.setAccount(account);
			lead.setAddress(l.getAddress());
			lead.setCity(l.getCity());
			lead.setCountry(l.getCountry());
			lead.setEmail(l.getEmail());
			lead.setFax(l.getFax());
			lead.setLeadDate(l.getLeadDate());
			lead.setName(l.getName());
			lead.setPhoneNum(l.getPhoneNum());
			lead.setProductInterest(l.getProductInterest());
			lead.setCurrentState(newState);	
			lead.setInterestedCustomer(l.getInterestedCustomer());	
			repository = RepositoryFactory.getRepository(SMSConstants.LEAD);
			long id = IDGenerator.getNextId();
			lead.setSmsObjId(id);
			repository.insert(new Long(id),lead);	
			//	System.out.println("Creating new lead object..."+ id );
			
			MarketingRepository.updateLead(smsObj.getSmsObjId(),(Lead)smsObj );
			System.out.println("Successfully imported lead" );
			
			
		}
		
	}
	
	
	public String getStateName(){
		return NAME;
	}

}
